﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using Newtonsoft.Json;

namespace WP_Customer_ShopMob.Helper
{
    public static class IsolatedStorage
    {
        public static void SaveData()
        {
            IsolatedStorageSettings.ApplicationSettings["datetime"] = DateTime.Now;
            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        public static void Save<T>(T objectToSerialise, String fileName)
        {
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Create);
            try
            {
                using (var writer = new StreamWriter(stream))
                {
                    string s = JsonConvert.SerializeObject(objectToSerialise);
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Serialize(writer, objectToSerialise);
                }
            }
            catch (Exception emAll)
            {
                throw emAll;
            }
        }

        public static T Load<T>(String fileName) where T : new()
        {
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            if (store.FileExists(fileName))
            {
                //store.DeleteFile("compte");
                //store.DeleteFile("categories");
                //store.DeleteFile("articles");
                IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Open);
                try
                {
                    using (var reader = new JsonTextReader(new StreamReader(stream)))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        T _return = new T();
                        _return = serializer.Deserialize<T>(reader);
                        stream.Close();
                        return _return;
                    }
                }
                catch (Exception)
                {
                    stream.Close();
                    return default(T);
                }
            }
            else
                return default(T);
        }
    }
}
